class SceneManager {
  constructor() {
    this.scenes = new Map();
    this.currentScene = null;
    this.transition = {
      inProgress: false,
      duration: 1000,
      progress: 0,
      type: 'fade'
    };
  }

  addScene(name, scene) {
    this.scenes.set(name, {
      update: scene.update,
      render: scene.render,
      onEnter: scene.onEnter,
      onExit: scene.onExit
    });
  }

  switchTo(sceneName) {
    if (!this.scenes.has(sceneName)) return;

    if (this.currentScene) {
      this.transition.inProgress = true;
      this.transition.progress = 0;
      this.scenes.get(this.currentScene).onExit?.();
    }

    this.currentScene = sceneName;
    this.scenes.get(sceneName).onEnter?.();
  }

  update(deltaTime) {
    if (this.transition.inProgress) {
      this.transition.progress += deltaTime;
      if (this.transition.progress >= this.transition.duration) {
        this.transition.inProgress = false;
      }
    }
    this.scenes.get(this.currentScene)?.update(deltaTime);
  }

  render(ctx) {
    this.scenes.get(this.currentScene)?.render(ctx);
    
    if (this.transition.inProgress) {
      const alpha = Math.min(this.transition.progress / this.transition.duration, 1);
      ctx.fillStyle = `rgba(0,0,0,${alpha})`;
      ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    }
  }
}

export const sceneManager = new SceneManager();